<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.0.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  
  <link rel="stylesheet" href="/lib/animate-css/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"jiapengcai.gitee.io","root":"/","scheme":"Gemini","version":"8.0.0-rc.5","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":false,"nav":null,"activeClass":"valine"},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false};
  </script>

  <meta name="description" content="最近在工作上遇到这样一个场景，有以下两张表：         table1table2                                      page_idpage_name                             1页面1                             2页面2">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL函数GROUP_CONCAT的使用">
<meta property="og:url" content="https://jiapengcai.gitee.io/posts/42624/index.html">
<meta property="og:site_name" content="PenG">
<meta property="og:description" content="最近在工作上遇到这样一个场景，有以下两张表：         table1table2                                      page_idpage_name                             1页面1                             2页面2">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-08-17T15:24:14.000Z">
<meta property="article:modified_time" content="2019-08-18T10:33:03.499Z">
<meta property="article:author" content="Jiapeng Cai">
<meta property="article:tag" content="编程">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://jiapengcai.gitee.io/posts/42624/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>MySQL函数GROUP_CONCAT的使用 | PenG</title>
  






  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <main class="main">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader">
        <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">PenG</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <section class="post-toc-wrap sidebar-panel">
      </section>
      <!--/noindex-->

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jiapeng Cai"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">Jiapeng Cai</p>
  <div class="site-description" itemprop="description">Life can be programmed.</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">9</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/jiapengcai" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;jiapengcai" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:635793@gmail.com" title="E-Mail → mailto:635793@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </section>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </header>

      
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/jiapengcai" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div id="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


      <div class="main-inner">
        

        <div class="content post posts-expand">
          

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://jiapengcai.gitee.io/posts/42624/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="Jiapeng Cai">
      <meta itemprop="description" content="Life can be programmed.">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PenG">
    </span>

    
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MySQL函数GROUP_CONCAT的使用
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-08-17 23:24:14" itemprop="dateCreated datePublished" datetime="2019-08-17T23:24:14+08:00">2019-08-17</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-08-18 18:33:03" itemprop="dateModified" datetime="2019-08-18T18:33:03+08:00">2019-08-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%8A%80%E6%9C%AF/" itemprop="url" rel="index"><span itemprop="name">技术</span></a>
                </span>
            </span>

          
            <span id="/posts/42624/" class="post-meta-item leancloud_visitors" data-flag-title="MySQL函数GROUP_CONCAT的使用" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/posts/42624/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/posts/42624/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>最近在工作上遇到这样一个场景，有以下两张表：</p>
<table frame=void>
  <tr>
    <th>table1</th><th>table2</th>
  </tr>
  <tr>
    <td>
      <table>
        <tr>
          <th>page_id</th><th>page_name</th>
        </tr>
        <tr>
          <td>1</td><td>页面1</td>
        </tr>
        <tr>
          <td>2</td><td>页面2</td>
        </tr>
      </table>
    </td>
    <td>
      <table>
        <tr>
        <th>page_id</th><th>channel_name</th>
        </tr>
        <tr>
        <td>1</td><td>渠道1</td>
        </tr>
        <tr>
        <td>1</td><td>渠道2</td>
        </tr>
        <tr>
        <td>1</td><td>渠道3</td>
        </tr>
        <tr>
        <td>2</td><td>渠道4</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

<p>现在要查出page_id为1时对应的channel_name有哪些，并以逗号隔开的字符串在页面上进行展示。页面上要展示的效果如下所示：</p>
<table>
  <tr>
    <th>page_name</th><th>channel_name_list</th>
  </tr>
  <tr>
    <td>页面1</td><td>渠道1,渠道2,渠道3</td>
  </tr>
</table> 
<a id="more"></a> 

<p>当时的第一想法是，通过语句</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> a.page_name, b.channel_name</span><br><span class="line"><span class="keyword">from</span> table1 a, table2 b</span><br><span class="line"><span class="keyword">where</span> a.page_id = b.page_id</span><br><span class="line"><span class="keyword">and</span> a.page_id = <span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>查询出页面1所对应的渠道列表，然后在程序里拼接成字符串。但后来想了一下，MySQL已经有CONCAT函数用于字符串拼接，那是否也有类似的用于将查询出来的字符串组进行拼接？打开Bing搜索“mysql 查询 字符串 拼接”，还真的有，这个函数就是GROUP_CONCAT。在MySQL官方文档里查找这个函数，解释如下：</p>
<ul>
<li>GROUP_CONCAT(expr)  </li>
</ul>
<p>此函数将一组非空字符串进行拼接并返回。如果字符串组里没有非空值，则返回NULL。完整的语法如下所示：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">GROUP_CONCAT([DISTINCT] expr [,expr ...]</span><br><span class="line">             [ORDER BY &#123;unsigned_integer | col_name | expr&#125;</span><br><span class="line">                 [ASC | DESC] [,col_name ...]]</span><br><span class="line">             [SEPARATOR str_val])</span><br></pre></td></tr></table></figure>
<p>用法如下所示：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT student_name,</span><br><span class="line">         GROUP_CONCAT(test_score)</span><br><span class="line">       FROM student</span><br><span class="line">       GROUP BY student_name;</span><br></pre></td></tr></table></figure>
<p>或者</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT student_name,</span><br><span class="line">         GROUP_CONCAT(DISTINCT test_score</span><br><span class="line">                      ORDER BY test_score DESC SEPARATOR &#x27; &#x27;)</span><br><span class="line">       FROM student</span><br><span class="line">       GROUP BY student_name;</span><br></pre></td></tr></table></figure>
<p>在MySQL里，我们可以通过组合表达式来获取我们想要的拼接值。例如，通过使用DISTINCT关键字，我们可以去除重复的值。通过为ORDER BY关键字后面的字段名添加DESC关键字，我们可以令最终的拼接值是降序排列的。默认是升序，我们也可以明确指定ASC关键字。拼接字符串默认用英文逗号隔开。如果想要替换默认分隔符，可以通过SEPARATOR关键字来指定。例如，我们可以用SEPARATOR ‘’的方式来去除拼接字符串之间的分隔符。<br>返回的拼接字符串将受限于系统变量group_concat_max_len的值，默认值为1024，如果超出设定的值，则字符串将被截短。虽然返回值的有效最大长度也受限于max_allowed_packet的值，但我们依旧可以将group_concat_max_len值调大。<br>在运行时修改group_concat_max_len的句法如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SET</span> [<span class="keyword">GLOBAL</span> | <span class="keyword">SESSION</span>] group_concat_max_len = val;</span><br></pre></td></tr></table></figure>
<p>此处的val为无符号的整型值。<br>返回值是否为二进制字符串取决于参数是否为二进制字符串。但group_concat_max_len的值小于等于512时，返回值的类型为VARCHAR或VARBINARY，超过这个值时，返回值的类型为TEXT或者BLOB。</p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Jiapeng Cai
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://jiapengcai.gitee.io/posts/42624/" title="MySQL函数GROUP_CONCAT的使用">https://jiapengcai.gitee.io/posts/42624/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E7%BC%96%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> 编程</a>
              <a href="/tags/MySQL/" rel="tag"><i class="fa fa-tag"></i> MySQL</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/40514/" rel="prev" title="RabbitMQ Spring-AMQP官方教程（六）--RPC">
      <i class="fa fa-chevron-left"></i> RabbitMQ Spring-AMQP官方教程（六）--RPC
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/24843/" rel="next" title="单元测试">
      单元测试 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



        </div>
        
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fab fa-affiliatetheme"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jiapeng Cai</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>


  















  

  

  


<script>
NexT.utils.loadComments('#valine-comments', () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', () => {
    new Valine(Object.assign({
      el  : '#valine-comments',
      path: location.pathname,
    }, {"enable":true,"appId":"9R584ubklhG3KtIebsybj2Fg-gzGzoHsz","appKey":"hTQwNb5tpJrtED29EvBeAshK","placeholder":"Just go go","avatar":"mm","meta":["nick","mail","link"],"pageSize":10,"language":"zh-cn","visitor":true,"comment_count":true,"recordIP":false,"serverURLs":null,"enableQQ":false,"requiredFields":[]}
    ));
  }, window.Valine);
});
</script>

</body>
</html>
